﻿#include "MediaTools.h"
#include "ui_MediaTools.h"
#include <QFrame>

#include "QyMultiMedia/YAvi.h"
#include "QyMultiMedia/YGif.h"
#include "QyMultiMedia/FpsTimer.h"
#include "QyMultiMedia/MediaCommon.h"

// add by liq test
#include <QMessageBox>
// add by liq 15
#include <QMouseEvent>
//#include <globalmouseevent.h>
#include <QPainter>
//#include "HookThread.h"
#include "controller/WindowManager.h"

// add by liq 15
static QString LAST_SAVE_PATH = "";

MediaTools::MediaTools(const QString& lastSavePath, QWidget *parent) :
    YToolWidget(parent),
    ui(new Ui::MediaTools)
{
    ui->setupUi(this);
    connect(ui->btnRecord, &QRadioButton::clicked, [this]{
        if(isStarted){
            save();
        }else{
            ui->btnAvi->setEnabled(false);
            ui->btnGif->setEnabled(false);
            ui->intFps->setEnabled(false);
            isStarted = true;
            ui->btnRecord->setText(QString::fromLocal8Bit("结束录制"));
            // add by liq 15
            // 设置样式表
            ui->btnRecord->setStyleSheet(
                "QPushButton{"
                    "background-color: #008000;"
                    "font: 10pt \"黑体\";"
                    "color: rgb(255, 255, 255);"
                    "border-radius: 2px;"
                    "min-height: 26px;"
                    "min-width: 68px;"
                    "border: none;"
                "}"
                "QPushButton:pressed{"
                    "border: none;"
                    "background-color: #007800;"
                "}"
                "QPushButton:hover{"
                    "border: none;"
                    "background-color: #009000;"
                "}"
            );
            start();
        }
    });
    ui->btnCancel->setText(QChar(0xf00d));

    // add by liq 15
    // 不在本线程监听，会导致鼠标卡顿或录屏失败，改为HookThread中监听
//    connect(GlobalMouseEvent::getInstance(), &GlobalMouseEvent::mouseEvent, this, &MediaTools::on_mouseEvent);
    LAST_SAVE_PATH = lastSavePath;
}

MediaTools::~MediaTools()
{
    stop();
    for(QWidget* line : lines){
        line->deleteLater();
    }
    delete ui;
}

QFrame* getOneFrame()
{
    static QString styleSheet = "background-color: red;";
    QFrame* line = new QFrame;
    line->setWindowFlags(Qt::ToolTip | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint);
    line->setStyleSheet(styleSheet);
    return line;
}

void MediaTools::tack(const QRect &rect, const QRect& originScreenRect)
{
    recordArea = rect;
    set(rect, originScreenRect);

    QFrame* leftline = getOneFrame();
    leftline->setGeometry(rect.x(), rect.y(), 2, rect.height());
    leftline->show();
    lines.append(leftline);

    QFrame* topline = getOneFrame();
    topline->setGeometry(rect.x(), rect.y(), rect.width(), 2);
    topline->show();
    lines.append(topline);

    if(rect.right() < originScreenRect.width()){
        QFrame* rightline = getOneFrame();
        rightline->setGeometry(rect.right()-1, rect.y(), 2, rect.height());
        rightline->show();
        lines.append(rightline);
    }
    if(rect.bottom() < originScreenRect.height()){
        QFrame* bottomline = getOneFrame();
        bottomline->setGeometry(rect.x(), rect.bottom()-1, rect.width(), 2);
        bottomline->show();
        lines.append(bottomline);
    }
}

void MediaTools::timeout()
{
    if(selected) return;
    YToolWidget::timeout();
    for(QWidget* line : lines){
        line->raise();
    }
}

void MediaTools::start()
{
    // add by liq 15
    // 全局鼠标监听事件安装
//    bool ret = GlobalMouseEvent::installMouseEvent();
    m_hookThread = new HookThread;
    connect(m_hookThread, &HookThread::sig_mouseEvent, this, &MediaTools::on_mouseEvent);
    m_hookThread->start();

    if(ui->btnAvi->isChecked()){
        type = AVI;
        media = new YAvi(this);
    }else{
        type = GIF;
        media = new YGif(this);
    }
    media->open();
    media->setVideo(recordArea.width()-4, recordArea.height()-4, ui->intFps->value());

    timer = new FpsTimer(ui->intFps->value(), this);
    connect(timer, &FpsTimer::timeout, [this]{
        // modify by liq 14
//        media->addFrame(MediaCommon::grabWindow(0, recordArea.x(), recordArea.y(), recordArea.width(), recordArea.height()));
//        media->addFrame(MediaCommon::grabWindowForGif(0, recordArea.x()+2, recordArea.y()+2, recordArea.width()-4, recordArea.height()-4));
        QImage image = MediaCommon::grabWindowForGif(0, recordArea.x()+2, recordArea.y()+2, recordArea.width()-4, recordArea.height()-4);
        // 鼠标左键压下时进行标记
        if(isMouseLeftButtonPressed){
            QPainter painter(&image);
            painter.setPen(Qt::NoPen); //不设置画笔,不绘制边界线
            QColor color(Qt::yellow);
            color.setAlpha(150); //其中，参数为透明度，取值范围为0~255，数值越小越透明
            QBrush brush(color);
            painter.setBrush(brush);
            painter.drawEllipse(x - 15, y - 15, 30, 30);
        }
        // 鼠标右键压下时进行标记
        if(isMouseRightButtonPressed){
            QPainter painter(&image);
            painter.setPen(Qt::NoPen); //不设置画笔,不绘制边界线
            QColor color(Qt::green);
            color.setAlpha(150); //其中，参数为透明度，取值范围为0~255，数值越小越透明
            QBrush brush(color);
            painter.setBrush(brush);
            painter.drawEllipse(x - 15, y - 15, 30, 30);
        }
        media->addFrame(image);

        count++;
        ui->lblTotalFrames->setText(QString::number(count));
    });
    timer->start();
    count = 0;
}

void MediaTools::save()
{
    printf(__func__);
    timer->stop();
    selected = true;
    // modify by liq 15
    QString writeDir = LAST_SAVE_PATH;
    QString fileName = media->defaultFileDialog(writeDir);
    selected = false;
    if(fileName.isEmpty()) return;
    media->save(fileName);
    // add by liq 15
    emit WindowManager::instance()->sigUpdateLastSavePath(fileName, true);
    // 需要更新LAST_SAVE_PATH
    QFileInfo fileinfo(fileName);
    LAST_SAVE_PATH = fileinfo.absoluteFilePath();
    deleteLater();

    // add by liq 15
//    bool ret = GlobalMouseEvent::removeMouseEvent();
    m_hookThread->close();
}

void MediaTools::stop()
{
//    if(type == AVI){
//    }else /*if(type == GIF)*/{
//    }
    if(timer){
        timer->stop();
    }
    if(media){
        media->close();
        // add by liq 15
    //    bool ret = GlobalMouseEvent::removeMouseEvent();
        m_hookThread->close();
    }
}

// add by liq 15
/**
 * @brief       全局鼠标事件
 * @param event
 */
void MediaTools::on_mouseEvent(QMouseEvent* event){
    switch (event->type())
    {
        case QEvent::MouseButtonPress:   // 鼠标按下
        {
            switch (event->button())
            {
                case Qt::LeftButton:
                {
                    QPoint point = mapFromParent(event->pos());
                    x = point.x() - 2;
                    y = event->pos().y() - recordArea.y() - 2;
                    isMouseLeftButtonPressed = true;
                    break;
                }
                case Qt::RightButton:
                {
                    QPoint point = mapFromParent(event->pos());
                    x = point.x() - 2;
                    y = event->pos().y() - recordArea.y() - 2;
                    isMouseRightButtonPressed = true;
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case QEvent::MouseButtonRelease:     // 鼠标抬起
        {
            switch (event->button())
            {
                case Qt::LeftButton:
                {
                    QPoint point = mapFromParent(event->pos());
                    x = point.x() - 2;
                    y = event->pos().y() - recordArea.y() - 2;
                    isMouseLeftButtonPressed = false;
                    break;
                }
                case Qt::RightButton:
                {
                    QPoint point = mapFromParent(event->pos());
                    x = point.x() - 2;
                    y = event->pos().y() - recordArea.y() - 2;
                    isMouseRightButtonPressed = false;
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case QEvent::MouseMove:     // 鼠标移动
        {
            if(isMouseLeftButtonPressed || isMouseRightButtonPressed){
                QPoint point = mapFromParent(event->pos());
                x = point.x() - 2;
                y = event->pos().y() - recordArea.y() - 2;
            }
            break;
        }
        default:
            break;
    }
}
